package com.douqu.game.core.entity.ext.data.mall;

import com.bean.core.buffer.ByteBuffer;
import com.douqu.game.core.entity.Player;
import com.douqu.game.core.entity.ext.data.BaseData;
import com.douqu.game.core.factory.ConstantFactory;
import com.douqu.game.core.factory.DataFactory;
import com.douqu.game.core.util.CoreUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
* Created by ${ZhaoLong} on 2018/3/28.
*/
public class MallData extends BaseData {

    /**
     * <物品的唯一id，我购买的物品数量>*
     */
    private Map<Integer, Integer> buyGoodsMap;

    private long lastBuyTime;

    Player player;

    public MallData(Player player) {
        this.player = player;
        buyGoodsMap = new ConcurrentHashMap<>();
    }

    @Override
    public void init() {

    }

    @Override
    public void checkInit() {

    }

    @Override
    public void reset() {
        buyGoodsMap.clear();
    }

    @Override
    public void checkReset() {
        if(!CoreUtils.isTodayByOffset(lastBuyTime, DataFactory.currentTime, ConstantFactory.DEFAULT_RESET_FRESH_TIMES_HOUR)){
            reset();
        }
    }

    @Override
    public void writeTo(ByteBuffer buffer)
    {
        buffer.writeShort(buyGoodsMap.size());
        for(Map.Entry<Integer, Integer> entry : buyGoodsMap.entrySet())
        {
            buffer.writeInt(entry.getKey());
            buffer.writeInt(entry.getValue());
        }

        buffer.writeLong(lastBuyTime);
        buffer.writeBoolean(false);
    }

    @Override
    public void loadFrom(ByteBuffer buffer) {
        int size = buffer.readShort();
        Integer key;
        Integer value;
        for (int i = 0; i < size; i++) {
            key = buffer.readInt();
            value = buffer.readInt();
            buyGoodsMap.put(key, value);
        }
        lastBuyTime = buffer.readLong();
        buffer.readBoolean();
    }

    public Map<Integer, Integer> getBuyGoodsMap() {
        return buyGoodsMap;
    }

    /**
     * 查询当前我拥有的数量
     *
     * @param goodId 商品的唯一id
     * @return
     */
    public int checkHasBuyCount(int goodId) {
        if (buyGoodsMap.get(goodId) != null) {
            int value = buyGoodsMap.get(goodId);
            return value;
        }
        return 0;
    }

    /**
     * 添加购买的的数据
     *
     * @param goodId     商品的唯一id
     * @param buyAccount 购买的数量
     */
    public void addAuctionData(int goodId, int buyAccount) {
        lastBuyTime = DataFactory.currentTime;
        Integer integer = buyGoodsMap.get(goodId);
        Integer value = integer == null ? buyAccount : (integer.intValue() + buyAccount);
        buyGoodsMap.put(goodId, value);
    }


    @Override
    public String toString() {
        return "MallData{" +
                "buyGoodsMap=" + buyGoodsMap +
                '}' + super.toString();
    }
}
